package meilisearchx

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/gookit/color"
	"github.com/meilisearch/meilisearch-go"
)

type Stu struct {
	Id     int      `json:"id"`
	Title  string   `json:"title"`
	Genres []string `json:"genres"`
}

func Add(client meilisearch.ServiceManager) {
	// An index is where the documents are stored.
	index := client.Index("movies")
	index.DeleteAllDocuments()
	// If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
	documents := []Stu{
		Stu{Id: 1, Title: "Carol", Genres: []string{"Romance", "Drama"}},
		Stu{Id: 2, Title: "Wonder Woman", Genres: []string{"Action", "Adventure"}},
		Stu{Id: 3, Title: "Life of Pi", Genres: []string{"Adventure", "Drama"}},
		Stu{Id: 4, Title: "Mad Max: Fury Road", Genres: []string{"Adventure", "Science Fiction"}},
		Stu{Id: 5, Title: "Moana", Genres: []string{"Fantasy", "Action"}},
		Stu{Id: 6, Title: "Philadelphia", Genres: []string{"Drama"}},
	}

	task, err := index.AddDocuments(documents)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	color.Blueln(task.TaskUID)
}
func Search(client meilisearch.ServiceManager) {
	searchRes, err := client.Index("movies").Search("Life",
		&meilisearch.SearchRequest{
			Limit: 10,
		})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	color.Yellowln(searchRes.Hits)
}
func CustomSearch(client meilisearch.ServiceManager) {
	index := client.Index("movies")
	index.UpdateFilterableAttributes(&[]string{"id", "genres"})

	searchRes, err := index.Search("wonder",
		&meilisearch.SearchRequest{
			AttributesToHighlight: []string{"*"},
		})
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var mm []Stu

	marshal, err := json.Marshal(searchRes.Hits)
	if err != nil {
		return
	}

	json.Unmarshal(marshal, &mm)

	for s, a := range mm {
		fmt.Println(s, a)
	}
}
